<!--
 * @Author: krsea 965837746@qq.com
 * @Date: 2025-03-10 08:36:48
 * @LastEditors: krsea 965837746@qq.com
 * @LastEditTime: 2025-03-11 09:01:39
 * @FilePath: \vue3-code\2305\week4\1.非父子组件之间的通信.html
 * @Description: 
 * 
 * Copyright (c) 2025 by ${git_name_email}, All Rights Reserved. 
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>非父子组件之间的通信</title>
    <!-- 引入 vue.js -->
    <script src="../js/vue.js"></script>
</head>

<body>
    <!-- div id 为 app 挂载点 -->
    <div id="app">
        <h2>组件A:向总线bus 上报事件</h2>
        <componenta></componenta>
        <h2>组件B:监听总线bus 的事件</h2>
        <my-component-b></my-component-b>

    </div>


    <!-- 使用 javascript 脚本 -->
    <script type="text/javascript">

        var bus = new Vue(); // 创建一个全局事件总线
        // 定义组件A
        Vue.component('componenta', { 
            template:`<div>
            <p>组件A</p>
            <hr>
            <button v-on:click="doClick">{{ counter }}</button>
        </div>`,
            data() {
                return {
                    counter: 0
                }
            },
            methods: {
                doClick() {
                    this.counter++;
                    // 向总线bus 上报事件 ( 事件名, 参数)
                    bus.$emit('btn-click', this.counter)
                }
            },
         });
         // 定义组件B
         Vue.component('my-component-b', { 
           template:`<div>
                <p>组件B</p>
                <hr>
                计数器: {{ counter }}
                <hr>
            </div>`,
            data() {
                return {
                    counter: 0
                }
            },
            created() {
                // 监听总线bus 的事件
                bus.$on('btn-click', (counter) => {
                    this.counter = counter;
                    // this.doChildClick();
                })
            },
            methods: {
                    
            }
         })

         var app = new Vue({
            el: '#app',
            data: {
                total: 0
            },
            methods: {
                doChildClick() {
                    this.total+= 1; // 累加
                }
            },
        })

    </script>
</body>

</html>